import Axios from "axios";
import router from "../router";
import { getToken } from "@/utils/auth";

export let $axios = Axios.create({
  baseURL:
    process.env.NODE_ENV === "production"
      ? "http://song2008/api"
      : "http://localhost:3000"
});
// request interceptor
$axios.interceptors.request.use(
  config => {
    let token = getToken("token");
    if (token) {
      config.headers.Authorization = `${token}`;
    }

    return config;
  },
  error => {
    // Do something with request error
    //console.log(error) // for debug
    Promise.reject(error);
  }
);
// respone拦截器
$axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          router.replace({
            path: "login",
            query: { redirect: router.currentRoute.fullPath } // 将跳转的路由path作为参数，登录成功后跳转到该路由
          });
      }
    }
    return Promise.reject(error.response);
  }
);
// get，post请求方法
export default {
  post(url, _data) {
    return $axios({
      method: "post",
      headers: {
        "Content-Type": "application/json"
      },
      url,
      data: _data
    });
  },
  get(url, params) {
    return $axios({
      method: "get",
      url,
      params
    });
  }
};
